const db = require('../db/index')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs');

const config = require('../config')

exports.login = (req, res) => {
    const admin_info = req.body
    const sql = 'select * from admin where name = ?'
    db.query(sql, admin_info.name, (err, results) => {
        if(err) return res.status(400).json(err)
        if(results.length !== 1) return res.status(400).json('用户不存在')
        const compareResults = bcrypt.compareSync(admin_info.password, results[0].password)
        if (!compareResults) return res.status(400).json('用户名或密码错误，请重新输入')
        // if(admin_info.password !== results[0].password) return res.status(400).json('用户名或密码错误，请重新输入')

        const admin = {
            id: results[0].id,
            name: results[0].name,
            identify: results[0].identify
        }

        const tokenStr = jwt.sign(admin, config.jwtSecretKey, {expiresIn: '10h'})

        res.json({
            status: 200,
            message: '登录成功',
            token: 'Bearer ' + tokenStr
        })
    })
}

exports.register = (req, res) => {
    const admin_info = req.body
    if (!admin_info.name || !admin_info.password) return res.json({status: 400, message: '用户名或密码为空'})
    const sql = 'select * from admin where name = ?'
    db.query(sql, admin_info.name, (err, results) => {
        if (err) return res.send({
            status: 404,
            message: err.message
        })
        if(results.length > 0) return res.status(400).json('用户名已被注册，请更改后重新注册！')

        admin_info.password = bcrypt.hashSync(admin_info.password, 10)
        const registerSql = 'insert into admin set ?'
        db.query(
            registerSql, 
            {name: admin_info.name, password: admin_info.password, identify: admin_info.identify},
            (err, results) => {
                if (err) return res.status(400).json(err)
                if(results.affectedRows !== 1) return res.send({status: 404, message: '注册失败，请稍后再试！'})
                res.json({
                    status: 200,
                    message: '注册成功',
                    name: admin_info.name,
                    password: admin_info.password,
                    identify: admin_info.identify
                })
            }
        )
    })
}